package org.windey.server;
import java.io.IOException;
import java.util.ArrayList;

import org.windey.Debug;

/**
 * 
 * 
 *
 */
public class WindeyServer
{
	private static WindeyServer server = null;
	/**
	 * 
	 */
	private boolean run;
	/**
	 * 
	 */
	private ClientConnectThread clientConnectThread;
	/**
	 * 
	 */
	private AppletConnectThread appletConnectThread;
	/**
	 * 
	 */
	private WindeyServerFileSettings settings;
	/**
	 * 
	 */
	private ArrayList<ClientConnection> clientConnections;
	/**
	 * 
	 */
	private ArrayList<AppletConnection> appletConnections;
	
	/**
	 * 
	 */
	private WindeyServer()
	{
		run = false;
		clientConnections = new ArrayList<ClientConnection>();
		appletConnections = new ArrayList<AppletConnection>();
		try {
			settings = new WindeyServerFileSettings();
		} catch (InvalidPropertyFileException e) {

			e.printStackTrace();
		}
		Debug.setDebug(true);
	}
	
	/**
	 * 
	 * @return
	 */
	public static synchronized WindeyServer getServer()
	{
		if (server == null)
		{
			server = new WindeyServer();
		}
		return server;
	}
	
	/**
	 * 
	 */
	public Object clone() throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException();
	}
	
	/**
	 * 
	 */
	public void startServer()
	{
		if (!run)
		{
			run = true;
			clientConnectThread = new ClientConnectThread(settings.getClientConnectPort(), this);
			clientConnectThread.start();
			appletConnectThread = new AppletConnectThread(settings.getAppletConnectPort(), this);
			appletConnectThread.start();
		}
	}
	
	/**
	 * 
	 * @throws IOException
	 */
	public void stopServer() throws IOException
	{
		if (run)
		{
			run = false;
			clientConnectThread.setRunning(false);
			appletConnectThread.setRunning(false);
		}
		for (ClientConnection cc : clientConnections)
		{
			cc.setRunning(false);
		}
		for (AppletConnection ac : appletConnections)
		{
			ac.setRunning(false);
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public boolean isRunning()
	{
		return run;
	}

	/**
	 * 
	 * @param cc
	 */
	public void addClientConnection(ClientConnection cc)
	{
		clientConnections.add(cc);
	}
	
	/**
	 * 
	 * @param ac
	 */
	public void addAppletConnection(AppletConnection ac)
	{
		appletConnections.add(ac);
	}
	
	/**
	 * 
	 * @param connectionKey
	 * @return
	 */
	public ClientConnection getClientConnection(String connectionKey)
	{
		ClientConnection result = null;
		for (ClientConnection cc : clientConnections)
		{
			if (cc.getConnectionKey().equalsIgnoreCase(connectionKey))
			{
				result = cc;
				break;
			}
		}
		return result;
	}
}
